<?php
/**
 * Created by PhpStorm
 * User: 陈志洪
 * Date: 2020/1/21
 * Time: 19:32
 */

namespace app\api\library\WeChat;

use app\api\model\Config as ConfigModel;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Http\StreamResponse;

/*
 * 小程序相关
 */
class MiniProgram
{
    private $app; // 小程序实例

    // 获取小程序实例
    public function __construct()
    {
        $config = [
            'app_id' => ConfigModel::getValueByName('appid'),
            'secret' => ConfigModel::getValueByName('secret'),

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];

        $this->app = Factory::miniProgram($config); // 实例话小程序
    }

    /**
     * 根据code 获取用户信息 openid 和 session_key
     * @param $code string code
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function getUserInfoByCode($code)
    {
        return $this->app->auth->session($code);
    }

    /**
     * @param $session string session_key code换取的
     * @param $iv string 前端传递 用于配合解密
     * @param $encryptedData string 前端传递 用于配合解密
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     */
    public function decryptData($session, $iv, $encryptedData)
    {
        return $this->app->encryptor->decryptData($session, $iv, $encryptedData);
    }

    /**
     * 生成带参数的小程序码
     * @param $url string 跳转路径
     * @param $id int 需要存入的参数
     * @return bool|int
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    public function getMPCode($url, $id)
    {
        $response = $this->app->app_code->getUnlimit('id=' . $id, [
            'page' => $url,
            'width' => 500,
        ]);

        $name = session_create_id();
        if ($response instanceof StreamResponse) {
            return $filename = $response->save(ROOT_PATH . 'public/wechat/', $name . '.png');
        }
    }

    /**
     * 一次性订阅消息
     * @param $templateId // 所需下发的订阅模板id
     * @param $openId // 接收者（用户）的 openid
     * @param $page  // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
     * @param $data
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @author: Lin Zhengyu
     * @since: 2020/7/25
     */
    public function templateMessage($templateId, $openId, $page, $data)
    {
        $data = [
            'template_id' => $templateId,
            'touser' => $openId,
            'page' => $page,
            'data' => $data
        ];

        return $this->app->subscribe_message->send($data);
    }
}
